package com.example.fw;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class AccountHelper extends HelperWithWebDriverBase {

	public AccountHelper(ApplicationManager applicationManager) {
		super(applicationManager);
	}

	public void signup(User user) {	
		openUrl("/");
		click(By.linkText("Signup for a new account"));
		type(By.name("username"), user.login);
		type(By.name("email"), user.email);
		click(By.cssSelector("input.button"));
		
		WebElement errorMessage = findElement(By.cssSelector("table.width50 tbody tr td p"));
		if (errorMessage != null) {
			throw new RuntimeException(errorMessage.getText()); 
		}
			
		pause(20000);
		String msg = manager.getMailHelper().getNewMail(user.login, user.password);
		String confirmationLink = getConfirmationLink(msg);
		openAbsoluteUrl(confirmationLink);
		
		type(By.name("password"), user.password);
		type(By.name("password_confirm"), user.password);
		click(By.cssSelector("input.button"));
	}

	public String getConfirmationLink(String text) {
		Pattern regex = Pattern.compile("http\\S*");
		Matcher matcher = regex.matcher(text);
		if (matcher.find()) {
			return matcher.group();
		} else {
			return "";
		}
	}
	
	public void login(User user) {
		openUrl("/");
		type(By.name("username"), user.login);
		type(By.name("password"), user.password);
		click(By.cssSelector("input.button"));
	}
	
	
	public String loggedUser() {
		WebElement element = findElement(By.cssSelector("td.login-info-left span"));
		return element.getText();
	}

	public void logout(){
		openUrl("/logout_page.php");
	}

	public void deleteUser(User user) {
	    // Удаляем пользователя из БД
		manager.getHibernateHelper().deleteUser(user);
	}

	public List<User> getUserList(){
		List<User> user = new ArrayList<User>();
		List<WebElement> rows = findElements(By.xpath("//tr[contains(@class, 'row')]//a[contains(@href, 'user_id')]"));
		for (WebElement row : rows) {
			String login = row.getText();
			user.add(new User().setLogin(login));
		} 
		return user;
	}
	
	public void openManageUserPage(){
		click(By.linkText("Manage"));
		click(By.linkText("Manage Users"));
	}
	
}
